package cn.xinliao.net;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class HttpOperation{
    public static HttpClient httpClient ;    
  
    /** 
     * @param url String
     * @param params Map<String, String>
     * @return String
     * @throws Exception 
     */  
    public static String postRequest(String url  
        , Map<String ,String> rawParams)  
    {  
        httpClient = CustomerHttpClient.getHttpClient();  
        //httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);//请求超时
       // httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);//读取超时
        try{  
            HttpPost post = new HttpPost(url);  
            
            List<NameValuePair> params = new ArrayList<NameValuePair>();  
            for(String key : rawParams.keySet())  
            {  
                params.add(new BasicNameValuePair(key , rawParams.get(key)));  
            }  

            post.setEntity(new UrlEncodedFormEntity(  
                params,HTTP.UTF_8));  
            
            HttpResponse httpResponse = httpClient.execute(post);  

            if (httpResponse.getStatusLine()  
                .getStatusCode() == HttpStatus.SC_OK)  
            {  
            	
            	Log.i("zeng", "getStatusCode:"+httpResponse.getStatusLine()  
                .getStatusCode());
                String result = EntityUtils  
                    .toString(httpResponse.getEntity());  
                return result;  
            }  
        }catch(Exception e){  
            e.printStackTrace();  
        }finally{  
            httpClient.getConnectionManager().shutdown();  
        }  
        return null;  
    }  
    
    /**
     * 
     * @param url	String
     * @param requestJSONStr	String
     * @return
     */
    public static String postRequestJSONFormat(String url, String requestJSONStr)  
    {  
    	HashMap<String, String> mapParams = new HashMap<String,String>()  ;
    	//mapParams.put(JSON_KEY_NAME, requestJSONStr) ;
    	//mapParams.put(AUTH_TOKEN_KEY, AUTH_TOKEN_VALUE) ;
    	
        return postRequest(url, mapParams)  ;
    } 
    
    /**
	 * 单例，返回同一个httpclient实例
	 */
	public static class CustomerHttpClient {
		private static final String CHARSET = HTTP.UTF_8;
		private static HttpClient customerHttpClient;

		private CustomerHttpClient() {
		}

		public static synchronized HttpClient getHttpClient() {
			if (null == customerHttpClient) {
				HttpParams params = new BasicHttpParams();
				// 设置一些基本参数
				HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
				HttpProtocolParams.setContentCharset(params, CHARSET);
				HttpProtocolParams.setUseExpectContinue(params, true);
				HttpProtocolParams
						.setUserAgent(
								params,
								"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
										+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
				// 超时设置
				/* 从连接池中取连接的超时时间 */
				ConnManagerParams.setTimeout(params, 1000);
				/* 连接超时 */
				HttpConnectionParams.setConnectionTimeout(params, 2000);
				/* 请求超时 */
				HttpConnectionParams.setSoTimeout(params, 4000);

				// 设置我们的HttpClient支持HTTP和HTTPS两种模式
				SchemeRegistry schReg = new SchemeRegistry();
				schReg.register(new Scheme("http", PlainSocketFactory
						.getSocketFactory(), 80));
				schReg.register(new Scheme("https", SSLSocketFactory
						.getSocketFactory(), 443));

				// 使用线程安全的连接管理来创建HttpClient
				ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
						params, schReg);
				customerHttpClient = new DefaultHttpClient(conMgr, params);
			}
			return customerHttpClient;
		}
	}
	/**
	 * 通过ftp上传文件
	 * @param url ftp服务器地址 如： 192.168.1.110
	 * @param port 端口如 ： 21
	 * @param username  登录名
	 * @param password   密码
	 * @param remotePath  上到ftp服务器的磁盘路径
	 * @param fileFullPath  要上传的文件全部路径路径，包括文件名
	 * @param fileName		要上传的文件名
	 * @param fileType		要上传的文件类型
	 * @return 1 ： 上传成功   0 ：失败
	 * 
	 * 第一个是路径，第3个是用户名，第4个是密码，
	 * 第5个是文件夹路径（注意第四个 是文件夹的路径，不用填完整的路径，
	 * 第6个是文件路径，第7个是文件的名字。
	 */
 public static String ftpUpload(String url, String port, String username,String password, 
		 String remotePath, String fileFullPath, String fileName, String fileType) {
	 FTPClient ftpClient = new FTPClient();
	 FileInputStream fis = null;
	 String returnMessage = "0";
	 try {
		 if(port == null || port == ""){
			 ftpClient.connect(url);
		 }else{
			 ftpClient.connect(url, Integer.parseInt(port));
		 }
		 
		 boolean loginResult = ftpClient.login(username, password);
		 int returnCode = ftpClient.getReplyCode();
		 if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功
			 if(remotePath != null && remotePath != ""){
				 ftpClient.makeDirectory(remotePath);
				// 设置上传目录
				 ftpClient.changeWorkingDirectory(remotePath);
			 }
			 ftpClient.setBufferSize(1024);
			 ftpClient.setControlEncoding("UTF-8");
			 ftpClient.enterLocalPassiveMode();
			 if(fileType.equals("pic")){
				 ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			 }
			 fis = new FileInputStream(fileFullPath);
			 ftpClient.storeFile(fileName, fis);
			 
			 returnMessage = "1";   //上传成功 		
		 } else {// 如果登录失败
			 returnMessage = "0";
			 }
		 		 

	 } catch (IOException e) {
		 e.printStackTrace();
		 throw new RuntimeException("FTP客户端出错！", e);
	 } finally {
		 //IOUtils.closeQuietly(fis);
	 try {
		 ftpClient.disconnect();
	 } catch (IOException e) {
		 	e.printStackTrace();
		 	throw new RuntimeException("关闭FTP连接发生异常！", e);
	 	}
	 }
	 return returnMessage;
 }
}
